import pygame
from game_items import *
from game_hud import *
import random


# import random
#
#
class Game(object):
    """游戏类"""

    def __init__(self):
        # 游戏主窗口
        self.main_window = pygame.display.set_mode(SCREEN_RECT.size)
        pygame.display.set_caption("飞机大战")
        # 游戏状态属性
        self.is_game_over = False
        self.is_pause = False

        # 精灵组属性
        self.all_group = pygame.sprite.Group()  # 所有精灵组
        self.enemies_group = pygame.sprite.Group()  # 敌机精灵组
        self.supplies_group = pygame.sprite.Group()  # 道具精灵组
        # 创建精灵
        # 背景精灵，向下移动
        GameSprite("/background.png", 1, self.all_group)
        # 背景精灵，交替滚动
        self.all_group.add(Background(False), Background(True))
        # 英雄精灵，静止不动
        self.hero = Plane(1000, 5, 0, "/hero.gif",
                          ["/hero%d.png" % i for i in range(1, 3)],
                          "/hero1.png", ["/hero_blowup_n%d.png" % i for i in range(1, 5)],
                          self.all_group)
        self.hero.rect.center = SCREEN_RECT.center  # 显示在屏幕中央
        # 指示器面板
        self.hud_panel = HudPanel(self.all_group)
        # hero = Plane(["/hero%d.png" % i for i in range(1, 3)], self.all_group)
        # hero.rect.center = SCREEN_RECT.center  # 显示在屏幕中央
        # 创建敌机
        self.create_enemies()
        # 英雄精灵
        self.hero = Hero(self.all_group)
        # 设置面板中炸弹数量
        self.hud_panel.show_bomb(self.hero.bomb_count)

        # 英雄精灵，静止不动
        # hero = GameSprite("/hero.gif", 0, self.all_group)
        # hero.rect.center = SCREEN_RECT.center  # 显示在屏幕中央

        # 指示器面板
        # self.hud_panel = HudPanel(self.all_group)
        # 英雄精灵，静止不动
        # self.hero = Plane(1000, 5, 0, "hero1.png",
        #                   ["/hero%d.png" % i for i in range(1, 3)],
        #                   "/hero2.png", ["/hero_blowup_n%d.png" % i for i in range(1, 5)],
        #                   self.all_group)
        # self.hero.rect.center = SCREEN_RECT.center  # 显示在屏幕中央
        # self.create_enemies()

    #
    def reset_game(self):
        """重置游戏"""
        self.is_game_over = False
        self.is_pause = False
        self.hud_panel.reset_panel()
        self.hero.rect.midbottom = HERO_DEFAULT_MTD_BOTTOM

    def event_handler(self):
        """事件监听
        :return:如果监听到推出事件，返回Ture，否则返回False
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return True
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                if self.is_game_over:  # 游戏已经结束
                    self.reset_game()  # 重新开始游戏
                else:
                    self.is_pause = not self.is_pause  # 切换暂停状态
            # 判断是否正在游戏
            if not self.is_game_over and not self.is_pause:
                # 监听取消英雄飞机无敌的事件
                if event.type == HERO_POWER_OFF_EVENT:
                    print ("取消无敌状态...")
                    # 设置英雄飞机状态
                    self.hero.is_power = False
                    # 取消定时器
                    pygame.time.set_timer(HERO_POWER_OFF_EVENT, 0)
                # 监听英雄飞机牺牲事件
                if event.type == HERO_DEAD_EVENT:
                    print("英雄牺牲了...")
                    # 生命计数 -1
                    self.hud_panel.lives_count -= 1
                    # 更新生命计数显示
                    self.hud_panel.show_bomb(self.hero.bomb_count)
                # 监听玩家按下“b”键
                if event.type == pygame.KEYDOWN and event.key == pygame.K_b:
                    # 引爆炸弹
                    score = self.hero.blowup(self.enemies_group)
                    # 更新炸弹数量显示
                    self.hud_panel.show_bomb(self.hero.bomb_count)
                    # 更新游戏得分，若关卡等级提升，则可以创建新类型的敌机
                    if self.hud_panel.increase_score(score):
                        self.create_enemies()
                    # for enemy in self.enemies_group.sprites():
                    #     enemy.hp = 0
                    # TODO测试炸弹数量变化
                    self.hud_panel.show_bomb(random.randint(0, 100))
                    # TODO测试生命计数数量变化
                    self.hud_panel.lives_count = random.randint(0, 10)
                    self.hud_panel.show_lives()
            return False

    #
    def start(self):
        """开始游戏"""
        clock = pygame.time.Clock()  # 游戏时钟
        frame_counter = 0
        while True:  # 开始游戏循环
            # 生命计数等于 0，表示游戏结束
            self.is_game_over = self.hud_panel.lives_count == 0
            if self.event_handler():  # 事件监听
                # return
                self.hud_panel.save_best_score()
                return
            # 判断游戏状态
            if self.is_game_over:
                # print('游戏已经结束，按下空格键重新开始...')
                self.hud_panel.panel_pause(True, self.all_group)
            elif self.is_pause:
                # print('游戏已经暂停，按下空格键继续...')
                self.hud_panel.panel_pause(False, self.all_group)
            else:
                # print('游戏进行中...')
                self.hud_panel.panel_resume(self.all_group)
                # 碰撞测试
                self.check_collide()
                # 获得当前时刻的按钮元组
                keys = pygame.key.get_pressed()
                # 水平移动基数
                move_hor = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
                # 垂直移动基数
                move_ver = keys[pygame.K_DOWN] - keys[pygame.K_UP]
                # 判断是否按下右方向键
                # if keys[pygame.K_RIGHT]:
                #     self.hero.rect.x += 10
                # 修改逐帧动画计数器
                frame_counter = (frame_counter + 1) % FRAME_INTERVAL
                # 更新 all_group 中所有精灵内容
                self.all_group.update(frame_counter == 0, move_hor, move_ver)
                self.all_group.update()
                # self.hero.hp -= 30
                # # 修改逐帧动画计数器
                # frame_counter = (frame_counter + 1) % FRAME_INTERVAL
                # # 更新 all_group 中所有精灵内容
                # self.all_group.update(frame_counter == 0)
                # 测试修改游戏得分
                # if self.hud_panel.increase_score(100):
                #     print("升级 %d" % self.hud_panel.level)
                #     self.create_enemies()
                # 更新all_group中所有精灵内容
                self.all_group.update()
                # # 修改逐帧动画计数器
                # frame_counter = (frame_counter + 1) % FRAME_INTERVAL
                # # 更新 all_group 中所有精灵内容
                # self.all_group.update(frame_counter == 0)
            # 绘制all_group中所有精灵
            self.all_group.draw(self.main_window)

            #                 self.hud_panel.panel_resume(self.all_group)
            #                 # 更新all_group中所有精灵内容
            #                 self.all_group.update()
            #                 # 绘制all_group中所有精灵
            #                 self.all_group.draw(self.main_window)
            #                 # TODO测试修改游戏得分
            #     if self.hud_panel.increase_score(100):
            #         print("升级 %d" % self.hud_panel.level)
            #                 #     self.create_enemies()
            #                 # 获得当前时刻的按键元组
            #                 keys = pygame.key.get_pressed()
            #                 # 判断是否按下右方向键
            #                 if keys[pygame.K_RIGHT]:
            #                     self.hero.rect.x += 10
            #                 # 修改逐帧动画计数器
            #                 frame_counter = (frame_counter + 1) % FRAME_INTERVAL
            #                 # 更新 all_group 中所有精灵内容
            #                 self.all_group.update(frame_counter == 0)
            #
            pygame.display.update()  # 更新显示
            clock.tick(60)  # 设置刷新帧率

    #
    def create_enemies(self):
        """ 根据关卡级别创建不同数量的敌机 """
        # 敌机精灵组中的精灵数量
        count = len(self.enemies_group.sprites())
        # 要添加到的精灵组
        groups = (self.all_group, self.enemies_group)
        # 判断关卡级别及已有的敌机数量
        if self.hud_panel.level == 1 and count == 0:
            for i in range(16):
                Enemy(0, 3, *groups)
        elif self.hud_panel.level == 2 and count == 16:
            for enemy in self.enemies_group.sprites():
                enemy.max_speed = 5
            # 创建敌机
            for i in range(8):
                Enemy(0, 5, *groups)
            for i in range(2):
                Enemy(1, 1, *groups)
        elif self.hud_panel.level == 3 and count == 26:
            # 提高敌机的最大速度
            for enemy in self.enemies_group.sprites():
                enemy.max_speed = 7 if enemy.kind == 0 else 3
            # 创建敌机
            for i in range(8):
                Enemy(0, 7, *groups)
            for i in range(2):
                Enemy(1, 3, *groups)
            for i in range(2):
                Enemy(2, 1, *groups)

    def check_collide(self):
        """ 碰撞检测"""
        # 检测英雄飞机和敌机的碰撞，若英雄飞机处于无敌状态，彼此不能碰撞
        if not self.hero.is_power:
            enemies = pygame.sprite.spritecollide(self.hero, self.enemies_group, False, pygame.sprite.collide_mask)
            # 过滤掉已经被摧毁的敌机
            enemies = list(filter(lambda x: x.hp > 0, enemies))
            # 是否撞到敌机
            if enemies:
                self.hero.hp = 0
            for enemy in enemies:
                enemy.hp = 0  # 摧毁发生碰撞的敌机


if __name__ == '__main__':
    pygame.init()
    Game().start()
    pygame.quit()
